<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\captcha\Captcha;
use think\Config;
use think\Db;
use think\Hook;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'captcha','update','checkVersion','upload','teachmode'];
    protected $noNeedRight = '*';

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 验证码
     * @param $id
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

    public function questions()
    {
        $resourceFile = input('resourceFile'); //音标商品测试题id
        $url = input('url','/file/soundmark/res/');
        $fileurl = fileurl($url,true);
        $sr['gunzipResPath_full'] = $resourceFile;
        $resource = json_decode(file_get_contents($sr['gunzipResPath_full']),true);
        if(isset($resource['parts'])){
            foreach ($resource['parts'] as $key=>$val){
                if(isset($val['children'])){
                    foreach ($val['children'] as $k=>$v){
                        if(isset($v['stem'])){
                            //图片地址替换
                            $originalString = $v['stem'];
                            $pattern = '/<img\s+[^>]*?\bsrc="\/catalogue([^"]*)"[^>]*>/i';
                            $replacement ='src="'.$fileurl.'catalogue';
                            $newString = preg_replace_callback($pattern, function($matches) use($replacement) {
                                return '<img ' . preg_replace('/src="\/catalogue/', $replacement, $matches[0]);
                            }, $originalString);


                            //填空替换输入框
                            $newString1 = preg_replace_callback('/{\#blank\#\}(\d+){\#\/blank\#}/', function($matches) {
                                // $matches[1] 将包含括号中的数字（在这个例子中是 1 或 2）
                                $vModelValue = 'tiankong' . $matches[1]; // 生成 v-model 的值
//                                return '<input v-model="tiankong" />';
                                return '<input v-model="' . htmlspecialchars($vModelValue, ENT_QUOTES, 'UTF-8') . '" />';
                            }, $newString);

                            // 使用正则表达式匹配 img 标签的 src 属性，并替换其值
                            $pattern = '/<img\s+[^>]*?src="(?:\.\.\/packages\/catalogue_\d+_\d+\/media\/[^"]*)"[^>]*>/i';
                            $newString2 = preg_replace_callback($pattern, function($matches) use($fileurl) {
                                // 提取原始 src 路径中的关键部分
                                $relativePath = $matches[0];
                                // 移除 "../packages/" 并添加新的 URL 前缀
                                $newPath = $fileurl . substr($relativePath, strpos($relativePath, 'catalogue_'));
                                // 替换整个 img 标签中的 src 属性
                                return preg_replace('/src="[^"]*"/', 'src="' . $newPath. '"', $matches[0]);
                            }, $newString1);

                            $resource['parts'][$key]['children'][$k]['stem'] = $newString2;

                            //图片替换

                        }
                    }
                }
            }
        }
        $data = [
            'resmain' => $fileurl,
            'resource'=>$resource,
            // 'resource_h5'=>$resource_h5,
        ];
        $this->success('请求成功',$data);
    }

    public function update()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $row = model('app\api\model\Version')
            ->order('newversion desc')
            ->find();
        $this->success('返回成功', $row);
    }

    // AppVersionController.php

    public function checkVersion()
    {
        $platform = input('post.platform'); // 获取平台类型
        $currentVersion = input('post.current_version'); // 获取当前版本号
        // 查询数据库获取最新版本信息
        $latestVersion = Db::name('version')
            ->where('platform', $platform)
            ->order('newversion', 'desc')
            ->find();
        // 如果没有找到对应平台的版本信息，返回空或错误信息
        if (!$latestVersion) {
            // 返回错误响应
            $this->error('未找到可用版本');
        }

        // 判断是否需要更新
        if (version_compare($currentVersion, $latestVersion['newversion'], '<')) {
            // 返回更新信息，包括版本号、描述、是否强制更新等
            // 还可以包括下载链接（如果需要）
            $data = [
                'version' => $latestVersion['newversion'],
                'content' => $latestVersion['content'],
                'enforce' => $latestVersion['enforce'],
                'downloadurl' => fileurl($latestVersion['downloadurl']) ?? '',
            ];
            $this->success('有新版本可用', $data);
        } else {
            // 当前版本已经是最新版本，返回相应信息
            $this->success('当前版本已是最新版本');
        }
    }

    public function checkTeacherversion()
    {
        $platform = input('post.platform'); // 获取平台类型
        $currentVersion = input('post.current_version'); // 获取当前版本号
        // 查询数据库获取最新版本信息
        $latestVersion = Db::name('teacherversion')
            ->where('platform', $platform)
            ->where('mode', 1)
            ->order('newversion', 'desc')
            ->find();
        // 如果没有找到对应平台的版本信息，返回空或错误信息
        if (!$latestVersion) {
            // 返回错误响应
            $this->error('未找到可用版本');
        }

        // 判断是否需要更新
        if (version_compare($currentVersion, $latestVersion['newversion'], '<')) {
            // 返回更新信息，包括版本号、描述、是否强制更新等
            // 还可以包括下载链接（如果需要）
            $data = [
                'version' => $latestVersion['newversion'],
                'content' => $latestVersion['content'],
                'enforce' => $latestVersion['enforce'],
                'mode' => $latestVersion['mode'],
                'downloadurl' => fileurl($latestVersion['downloadurl']) ?? '',
            ];
            $this->success('有新版本可用', $data);
        } else {
            // 当前版本已经是最新版本，返回相应信息
            $this->success('当前版本已是最新版本');
        }
    }

    public function teachmode()
    {
        $platform = input('post.platform'); // 获取平台类型
        $currentVersion = input('post.current_version'); // 获取当前版本号
        // 查询数据库获取最新版本信息
        $latestVersion = Db::name('teacherversion')
            ->where('platform', $platform)
            ->where('newversion', $currentVersion)
            ->find();
        if(empty($latestVersion)){
            $latestVersion['mode'] = 1;
        }
        $this->success('有新版本可用', $latestVersion);
    }
}
